package com.asynchfileupload.data;

/**  
* DiskStorageDataHandler.java - Interface IDataHandler.java implementation using the disk storage.  
* @author  Avinash Singh (349933)
* @version 1.0 
* @see IDataHandler
*/

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

public class DiskStorageDataHandler implements IDataHandler {

	private static final String storage_location = "C://temp";
	
	public boolean storeFile(InputStream is,String fileSessionID,String fileName,Map<String,String> inputParams)
	{
		boolean result = false;
		
		BufferedInputStream bis = new BufferedInputStream(is);
		OutputStream out=null;
		
		File dataFile = new File(storage_location + File.separator + fileName);
	
		try
		{
			if(!dataFile.exists()) dataFile.createNewFile();
			
			out= new FileOutputStream(dataFile);
			
			byte buf[]=new byte[1024*5];
			int len;
			
			while((len=bis.read(buf))>0)
			  out.write(buf,0,len);
			
			result = true;
			 
			System.out.println("DiskStorageDataHandler.java :storeFile() File Saved. " + fileName );
			
		}catch(Exception e)
		{
			System.out.println("DiskStorageDataHandler.java : Error in storing file");
			System.out.println("DiskStorageDataHandler.java : fileName " + fileName);
			System.out.println("DiskStorageDataHandler.java : inputParams " + inputParams);
			
			e.printStackTrace();
		}
		finally{
			
			  try{
				  if(out!=null)  out.close();		
				  if(bis!=null)bis.close();
				  if(is!=null)is.close();				  
			  }catch(Exception e)
			  {
				  e.printStackTrace();
			  }			  
		}		
		return result;
	}
	
	public boolean deleteFile(String fileSessionID,String fileName,Map<String,String> inputParams)
	{
		try{
			
			File dataFile = new File(storage_location + File.separator + fileName);
			
			if(dataFile.exists())
				dataFile.delete();
			
			System.out.println("DiskStorageDataHandler.java : deleteFile() File deleted. " + fileName );
			
		}catch(Exception ioe)
		{
			ioe.printStackTrace();
			return false;
		}
		
		return true;		
	}
}
